{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting d:\\java\\python\\w7\\tmp\\train-images-idx3-ubyte.gz\n",
      "Extracting d:\\java\\python\\w7\\tmp\\train-labels-idx1-ubyte.gz\n",
      "Extracting d:\\java\\python\\w7\\tmp\\t10k-images-idx3-ubyte.gz\n",
      "Extracting d:\\java\\python\\w7\\tmp\\t10k-labels-idx1-ubyte.gz\n",
      "hiiii\n"
     ]
    }
   ],
   "source": [
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "import tensorflow as tf\n",
    "data_dir = 'd:\\\\java\\\\python\\\\w7\\\\tmp'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)\n",
    "\n",
    "print('hiiii')\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "D:\\anaconda3\\envs\\tensorflow\\lib\\site-packages\\tensorflow\\python\\client\\session.py:1702: UserWarning: An interactive session is already active. This can cause out-of-memory errors in some cases. You must explicitly call `InteractiveSession.close()` to release resources held by the other session(s).\n",
      "  warnings.warn('An interactive session is already active. This can '\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From D:\\anaconda3\\envs\\tensorflow\\lib\\site-packages\\tensorflow\\python\\framework\\function.py:987: calling Graph.create_op (from tensorflow.python.framework.ops) with compute_shapes is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Shapes are always computed; don't use the compute_shapes as it has no effect.\n"
     ]
    }
   ],
   "source": [
    "# 创建默认InteractiveSession\n",
    "sess = tf.InteractiveSession()\n",
    "\n",
    "\n",
    "#########卷积网络会有很多的权重和偏置需要创建，先定义好初始化函数以便复用########\n",
    "# 给权重制造一些随机噪声打破完全对称（比如截断的正态分布噪声，标准差设为0.1）\n",
    "def weight_variable(shape):\n",
    "  initial = tf.truncated_normal(shape, stddev=0.1)\n",
    "  return tf.Variable(initial)\n",
    "# 设置偏置量\n",
    "def bias_variable(shape):\n",
    "  initial = tf.constant(0.1, shape=shape)\n",
    "  return tf.Variable(initial)\n",
    "\n",
    "\n",
    "########卷积层、池化层接下来重复使用的，分别定义创建函数########\n",
    "# tf.nn.conv2d是TensorFlow中的2维卷积函数\n",
    "def conv2d(x, W):\n",
    "  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n",
    "# 使用2*2的最大池化\n",
    "def max_pool_2x2(x):\n",
    "  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME')\n",
    "\n",
    "\n",
    "########正式设计卷积神经网络之前先定义placeholder########\n",
    "# x是特征，y_是真实label。将图片数据从1D转为2D。使用tensor的变形函数tf.reshape\n",
    "x = tf.placeholder(tf.float32, shape=[None, 784])\n",
    "y_ = tf.placeholder(tf.float32, shape=[None, 10])\n",
    "x_image = tf.reshape(x,[-1,28,28,1])\n",
    "\n",
    "\n",
    "########设计卷积神经网络########\n",
    "# 第一层卷积\n",
    "# 卷积核尺寸为5*5,1个颜色通道，32个不同的卷积核\n",
    "W_conv1 = weight_variable([5, 5, 1, 32])\n",
    "# 用conv2d函数进行卷积操作，加上偏置\n",
    "b_conv1 = bias_variable([32])\n",
    "# 把x_image和权值向量进行卷积，加上偏置项，然后应用swish激活函数\n",
    "h_conv1 = tf.nn.swish(conv2d(x_image, W_conv1) + b_conv1)\n",
    "# 对卷积的输出结果进行池化操作\n",
    "h_pool1 = max_pool_2x2(h_conv1)\n",
    "\n",
    "# 第二层卷积（和第一层大致相同，卷积核为64，这一层卷积会提取64种特征）\n",
    "W_conv2 = weight_variable([5, 5, 32, 64])\n",
    "b_conv2 = bias_variable([64])\n",
    "h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\n",
    "h_pool2 = max_pool_2x2(h_conv2)\n",
    "\n",
    "# 全连接层。隐含节点数1024。使用swish函数激活\n",
    "W_fc1 = weight_variable([7 * 7 * 64, 1024])\n",
    "b_fc1 = bias_variable([1024])\n",
    "h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])\n",
    "h_fc1 = tf.nn.swish(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n",
    "\n",
    "# 为了防止过拟合，在输出层之前加Dropout层\n",
    "keep_prob = tf.placeholder(tf.float32)\n",
    "h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n",
    "\n",
    "# 输出层。添加一个softmax层，就像softmax regression一样。得到概率输出。\n",
    "W_fc2 = weight_variable([1024, 10])\n",
    "b_fc2 = bias_variable([10])\n",
    "y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)\n",
    "\n",
    "\n",
    "########模型训练设置########\n",
    "# 定义loss function为cross entropy，\n",
    "coss_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y_conv),reduction_indices=[1]))\n",
    "#ross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_ logits=y)\n",
    "train_step = tf.train.GradientDescentOptimizer(0.05).minimize(cross_entropy)\n",
    "\n",
    "# 定义评测准确率的操作\n",
    "correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-->step 0, training accuracy 0.1000\n",
      "-->step 1000, training accuracy 0.9800\n",
      "-->step 2000, training accuracy 1.0000\n",
      "-->step 3000, training accuracy 0.9800\n",
      "-->step 4000, training accuracy 0.9800\n",
      "-->step 5000, training accuracy 1.0000\n",
      "-->step 6000, training accuracy 1.0000\n",
      "-->step 7000, training accuracy 1.0000\n",
      "-->step 8000, training accuracy 0.9600\n",
      "-->step 9000, training accuracy 1.0000\n",
      "卷积神经网络在MNIST数据集正确率: 0.9918\n"
     ]
    }
   ],
   "source": [
    "########开始训练过程########\n",
    "# 初始化所有参数\n",
    "tf.global_variables_initializer().run()\n",
    "\n",
    "# 训练（设置训练时Dropout的kepp_prob比率为0.5。mini-batch为50，进行10000次迭代训练，参与训练样本5万）\n",
    "# 其中每进行1000次训练，对准确率进行一次评测keep_prob设置为1，用以实时监测模型的性能\n",
    "for i in range(10000):\n",
    "  batch = mnist.train.next_batch(50)\n",
    "  if i%1000 == 0:\n",
    "    train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_: batch[1], keep_prob: 1.0})\n",
    "    print( \"-->step %d, training accuracy %.4f\"%(i, train_accuracy))\n",
    "  train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})\n",
    "# 全部训练完成之后，在最终测试集上进行全面测试，得到整体的分类准确率\n",
    "print(\"卷积神经网络在MNIST数据集正确率: %g\"%accuracy.eval(feed_dict={\n",
    "    x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
